﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using SCFHS.Code;
using System.Configuration;
using System.IO;

namespace SCFHS.Views
{
    public partial class CreateOrder : SysBase
    {
        #region Definitions

        #endregion

        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            ScriptManager.GetCurrent(this).RegisterPostBackControl(this.btnUpload);
            if (!IsPostBack)
            {
                Page.Form.Attributes.Add("enctype", "multipart/form-data");
            }
        }

        protected void btnCreateOrder_Click(object sender, EventArgs e)
        {
            try
            {

                if (hdfNewCreatedID.Value == "")
                {
                    hdfNewCreatedID.Value = controller.CreateOrder(txtPersonName.Text, txtOrderNo.Text, controller.ConvertDate(txtDate.Text), user.userID).ToString();

                    if (string.IsNullOrEmpty(hdfNewCreatedID.Value))
                    {
                        lblMessage.Text = Messages.CreateOrderFail;
                        lblMessage.CssClass = "error";
                        return;
                    }

                    lblMessage.Text = Messages.CreateOrderSuccess;
                    lblMessage.CssClass = "info";

                    //Show attachments process
                    mView.ActiveViewIndex = 1;

                }
                else
                {
                    bool result = controller.UpdateMainOrder(int.Parse(hdfNewCreatedID.Value), txtPersonName.Text, txtOrderNo.Text, controller.ConvertDate(txtDate.Text));

                    if (!result)
                    {
                        lblMessage.Text = Messages.OrderUpdateFail;
                        lblMessage.CssClass = "error";
                        return;
                    }

                    lblMessage.Text = "تم تحديث الطلب بنجاح";
                    lblMessage.CssClass = "info";
                    mView.ActiveViewIndex = 1;
                }
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                if (ex.Number == 1062)
                {
                    lblMessage.Text = "رقم الطلب موجود مسبقا في النظام .. يرجي إستكمال الطلب او حذفه و إعادة إدخاله مرة اخري";
                    lblMessage.CssClass = "error";
                    btnProced.Visible = true;
                }

            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
                lblMessage.CssClass = "error";
            }
        }

        protected void btnProced_Click(object sender, EventArgs e)
        {
            order = controller.SelectMainOrderInfo(txtOrderNo.Text);
            if (order == null)
            {
                lblMessage.Text = "حدث خطأ في إستكمال بيانات الطلب";
                lblMessage.CssClass = "error";
                return;
            }

            hdfNewCreatedID.Value = order.orderID.ToString();
            mView.ActiveViewIndex = 1;
            lblMessage.Text = "";
            BindAttachmentFiles();
        }

        protected void btnUpdateOrder_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(hdfNewCreatedID.Value))
            {
                lblMessage.Text = Messages.UpdateOrderCantbeDone;
                lblMessage.CssClass = "error";
                return;
            }

            mView.ActiveViewIndex = 0;
            btnSave.Visible = true;
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            string uploadFolder = ConfigurationManager.AppSettings["UploadPath"].ToString();
            if (string.IsNullOrEmpty(uploadFolder))
            {
                lblMessage.Text = Messages.UploadFolderNotDefined;
                lblMessage.CssClass = "error";
                return;
            }
            string uploadFolderPath = Server.MapPath(uploadFolder) + "\\";
            string fullPath = string.Empty;
            string newFileName = string.Empty;
            string dublicateNewFileName = string.Empty;

            if (!fuAttach.HasFile)
            {
                lblUploadMessage.Text = Messages.UploadNoFile;
                lblUploadMessage.CssClass = "error";
                return;
            }
            try
            {
                newFileName = hdfNewCreatedID.Value + Path.GetExtension(fuAttach.FileName);
                newFileName = AttachmentsType.OrderAttachment.ToString() + "-" + newFileName;
                fullPath = uploadFolderPath + newFileName;
                int count = 0;
                while (File.Exists(fullPath))
                {
                    count++;
                    dublicateNewFileName = "({0})" + newFileName;
                    dublicateNewFileName = string.Format(dublicateNewFileName, count.ToString());
                    fullPath = uploadFolderPath + dublicateNewFileName;
                }

                fuAttach.PostedFile.SaveAs(fullPath);
            }
            catch (Exception)
            {
                throw;
            }
            if (!string.IsNullOrEmpty(dublicateNewFileName))
                newFileName = dublicateNewFileName;
            bool result = controller.AddAttachmentToOrder(int.Parse(hdfNewCreatedID.Value), newFileName, (int)AttachmentsType.OrderAttachment, user.userID);

            if (!result)
            {
                lblUploadMessage.Text = Messages.UploadFail;
                lblUploadMessage.CssClass = "error";
                return;
            }

            lblUploadMessage.Text = Messages.UploadSuccess;
            lblUploadMessage.CssClass = "info";
            BindAttachmentFiles();
        }

        protected void btnSaveOrder_Click(object sender, EventArgs e)
        {
            if (grdAttachmentFiles.Rows.Count == 0)
            {
                lblMessage.Text = "لا يمكن إنشاء طلب بدون مرفقات يجب إضافة مرفق واحد على الأقل";
                lblMessage.CssClass = "error";
                return;
            }
            bool result = controller.SaveMainOrder(int.Parse(hdfNewCreatedID.Value), user.userID);

            if (!result)
            {
                lblMessage.Text = "حدث خطأ ولم يتم الإنتهاء الطلب";
                lblMessage.CssClass = "error";
                return;
            }

            lblMessage.Text = "تم الإنتهاء من عملية إنشاء الطلب بنجاح";
            lblMessage.CssClass = "info";
            hdfNewCreatedID.Value = "";
            txtPersonName.Text = "";
            txtOrderNo.Text = "";
            txtDate.Text = "";
            BindAttachmentFiles();
            mView.ActiveViewIndex = 0;
        }


        #endregion

        #region Helper Methods
        void BindAttachmentFiles()
        {
            if (string.IsNullOrEmpty(hdfNewCreatedID.Value))
            {
                grdAttachmentFiles.DataSource = null;
                grdAttachmentFiles.DataBind();
                return;
            }
            int orderID = int.Parse(hdfNewCreatedID.Value);
            grdAttachmentFiles.DataSource = controller.ListAttachmentFiles(orderID, AttachmentsType.OrderAttachment);
            grdAttachmentFiles.DataBind();
            //hdfRowCount.Value = grdAttachmentFiles.Rows.Count.ToString();
        }
        #endregion

        protected void grdAttachmentFiles_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string attachID = string.Empty;
            bool Result = false;
            if (e.Keys["ID"] != null)
                attachID = e.Keys["ID"].ToString();
            if (!string.IsNullOrEmpty(attachID))
                Result = controller.DeleteAttachmentFiles(int.Parse(attachID));
            if (!Result)
            {
                lblUploadMessage.CssClass = "error";
                lblUploadMessage.Text = Messages.UploadDeleteFileFail;
                return;
            }
            try
            {
                string UploadPath = ConfigurationManager.AppSettings["UploadPath"].ToString();
                if (string.IsNullOrEmpty(UploadPath))
                {
                    lblUploadMessage.CssClass = "error";
                    lblUploadMessage.Text = Messages.UploadDeleteFileFail;
                    return;
                }
                string fileName = ((LinkButton)grdAttachmentFiles.Rows[e.RowIndex].FindControl("lblAttachmentPoint")).Text;
                UploadPath = Server.MapPath(UploadPath) + "/" + fileName;
                if (File.Exists(UploadPath))
                {
                    File.Delete(UploadPath);
                }
                else
                {
                    lblUploadMessage.CssClass = "error";
                    lblUploadMessage.Text = "تم حذف إرتباط الملف من قاعدة البيانات و حدث خطأ أثناء حذف الملف الفعلي";
                }
            }
            catch (Exception)
            {
                throw;
            }
            lblUploadMessage.CssClass = "info";
            lblUploadMessage.Text = Messages.UploadDeleteFileSuccess;
            BindAttachmentFiles();

        }

        protected void grdAttachmentFiles_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //e.Row.Attributes["onClick"] = "location.href='Upload/" + DataBinder.Eval(e.Row.DataItem, "AttachmentPath") + "'";
                e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';";
            }
        }

        protected void lblAttachmentPoint_Click(object sender, EventArgs e)
        {
            string UploadPath = ConfigurationManager.AppSettings["UploadPath"].ToString();
            if (string.IsNullOrEmpty(UploadPath))
            {
                lblUploadMessage.CssClass = "error";
                lblUploadMessage.Text = Messages.UploadDeleteFileFail;
                return;
            }
            string fileName = ((LinkButton)sender).Text;
            UploadPath = Server.MapPath(UploadPath) + "/" + fileName;
            if (File.Exists(UploadPath))
            {
                Response.Redirect(UploadPath);
            }
        }
    }
}